# 专门负责天气查询的Agent
from python_a2a import A2AServer, run_server, TaskStatus, TaskState, AgentCard, AgentSkill
import requests
import json
import os
from dotenv import load_dotenv

load_dotenv()

class WeatherAgent(A2AServer):
    def __init__(self, agent_card, mcp_url):
        super().__init__(agent_card=agent_card)
        self.mcp_url = mcp_url
        print(f"🌤️ WeatherAgent 初始化完成，MCP服务: {self.mcp_url}")

    def _call_mcp_tool(self, tool_name, params):
        """调用MCP工具"""
        try:
            tool_endpoint = f"{self.mcp_url}/tools/{tool_name}"
            response = requests.post(tool_endpoint, json=params, timeout=10)
            response.raise_for_status()
            
            tool_response_json = response.json()
            if tool_response_json.get("content"):
                parts = tool_response_json["content"]
                if isinstance(parts, list) and len(parts) > 0 and "text" in parts[0]:
                    return parts[0]["text"]
            return "工具执行成功"
        except Exception as e:
            return f"调用MCP工具失败: {str(e)}"

    def handle_task(self, task):
        """处理天气查询任务"""
        message_data = task.message or {}
        content = message_data.get("content", {})
        text = content.get("text", "")
        
        print(f"🌤️ WeatherAgent收到任务: {text}")
        
        # 解析请求
        request_data = json.loads(text) if text.startswith('{') else {"query": text}

        # 1) 协作请求（来自其他Agent的 collaboration_request）
        if request_data.get("type") == "collaboration_request":
            user_requirements = request_data.get("user_requirements", {})
            city = user_requirements.get("location") or user_requirements.get("city")
            if not city:
                response = {
                    "agent": "WeatherAgent",
                    "error": "协作请求缺少用户位置(location)",
                    "original_request": request_data
                }
            else:
                weather_info = self._call_mcp_tool("get_current_weather", {"city": city})
                weather_analysis = self._analyze_weather_for_activities(weather_info)
                # 简单3日模拟预报
                forecast = [
                    {"day": 1, "condition": "多云", "temp_high": 18, "temp_low": 11},
                    {"day": 2, "condition": "小雨", "temp_high": 16, "temp_low": 9},
                    {"day": 3, "condition": "晴", "temp_high": 20, "temp_low": 12}
                ]
                response = {
                    "type": "collaboration_response",
                    "agent": "WeatherAgent",
                    "weather_data": {
                        "current": weather_info,
                        "forecast_3day": forecast
                    },
                    "impact_analysis": {
                        "summary": "基础天气分析",
                        "outdoor_suitability": 7 if ("晴" in weather_info or "多云" in weather_info) else 4,
                        "indoor_recommendation": "雨" in weather_info
                    },
                    "negotiation_points": [],
                    "potential_conflicts": [],
                    "confidence_score": 0.6
                }

        # 2) 普通查询（包含 city 字段或 query 中自然语言）
        elif "city" in request_data:
            city = request_data["city"]
            weather_info = self._call_mcp_tool("get_current_weather", {"city": city})
            weather_analysis = self._analyze_weather_for_activities(weather_info)
            response = {
                "agent": "WeatherAgent",
                "city": city,
                "weather_raw": weather_info,
                "weather_analysis": weather_analysis,
                "suitable_for_outdoor": "晴" in weather_info or "多云" in weather_info,
                "temperature_info": self._extract_temperature(weather_info)
            }
        else:
            response = {
                "agent": "WeatherAgent",
                "error": "未指定查询城市",
                "message": text,
                "hint": "对于协作请求，请确保 user_requirements.location 已设置"
            }

        task.artifacts = [{"parts": [{"type": "text", "text": json.dumps(response, ensure_ascii=False)}]}]
        task.status = TaskStatus(state=TaskState.COMPLETED)
        print(f"🌤️ WeatherAgent回复: {response}")
        return task

    def _analyze_weather_for_activities(self, weather_info):
        """分析天气对活动的适宜性"""
        analysis = {
            "outdoor_activities": "不适宜",
            "indoor_activities": "适宜",
            "recommendations": []
        }
        
        if "晴" in weather_info:
            analysis["outdoor_activities"] = "非常适宜"
            analysis["recommendations"].append("户外景点、公园、爬山")
        elif "多云" in weather_info:
            analysis["outdoor_activities"] = "适宜"
            analysis["recommendations"].append("户外散步、观光")
        elif "雨" in weather_info:
            analysis["outdoor_activities"] = "不适宜"
            analysis["recommendations"].append("博物馆、购物中心、室内娱乐")
        elif "雪" in weather_info:
            analysis["outdoor_activities"] = "特殊适宜"
            analysis["recommendations"].append("滑雪、雪景观赏")
            
        return analysis

    def _extract_temperature(self, weather_info):
        """提取温度信息"""
        import re
        temp_match = re.search(r'(-?\d+\.?\d*)°C', weather_info)
        if temp_match:
            temp = float(temp_match.group(1))
            if temp > 25:
                return {"temp": temp, "comfort": "炎热", "clothing": "轻薄衣物"}
            elif temp > 15:
                return {"temp": temp, "comfort": "舒适", "clothing": "适中衣物"}
            elif temp > 5:
                return {"temp": temp, "comfort": "凉爽", "clothing": "保暖衣物"}
            else:
                return {"temp": temp, "comfort": "寒冷", "clothing": "厚重衣物"}
        return {"temp": None, "comfort": "未知", "clothing": "根据感觉穿衣"}

if __name__ == "__main__":
    agent_card = AgentCard(
        name="Weather Expert Agent",
        description="专业天气分析Agent，提供天气信息和活动建议",
        url="http://localhost:7003",
        version="1.0.0",
        skills=[
            AgentSkill(
                name="Weather Query",
                description="查询指定城市的天气信息"
            ),
            AgentSkill(
                name="Activity Recommendation",
                description="基于天气条件推荐适宜的活动类型"
            ),
            AgentSkill(
                name="Weather Analysis",
                description="分析天气对不同活动的影响"
            )
        ]
    )

    weather_agent = WeatherAgent(agent_card, "http://localhost:7001")
    
    print("🌤️ WeatherAgent 启动于 http://localhost:7003")
    run_server(weather_agent, host="0.0.0.0", port=7003)
